import express from 'express';
import bodyParser from 'body-parser';
import jwt from 'jsonwebtoken';
import cors from 'cors';

import user from './user.js';
import dept from './dept.js';
import menu from './menu.js';
import role from './role.js';
import dashboard from './dashboard.js';
import fs from 'fs';
export const app = express();
const port = 3000;
const secretKey = 'your_secret_key';

// 配置 CORS 中间件
app.use(cors({
  origin: 'http://localhost:5173', // 允许所有前端域名
  credentials: true // 允许发送凭证
}));
// uploads文件夹下的文件可以通过 /uploads 访问
app.use('/uploads', express.static('uploads'));
app.use(bodyParser.urlencoded({ extended: false }));


app.use(bodyParser.json());
app.use('/api/user', user);
app.use('/api/dept', dept);
app.use('/api/menu', menu);
app.use('/api/role', role);
app.use('/api/dashboard', dashboard);


app.post('/api/login', (req, res) => {
  const { username, password } = req.body;
  if (username === 'admin' && password === 'admin') {
    const token = jwt.sign({ username }, secretKey, { expiresIn: '10000h' });
    return res.json({
      success: true,
      code: 100,
      message: '登录成功',
      data: {
        token
      }
    });
  }
  res.json({
    success: false,
    code: 400,
    message: '登录失败',
    data: null
  });
});
app.get('/api/userInfo', (req, res) => {
  // 获取请求头中的 token
  const token = req.headers['authorization'];
  if (!token) {
    return res.json({
      success: false,
      code: 401,
      message: '未登录',
      data: null
    });
  }
  try {
    // 验证 token
    const userInfo = jwt.verify(token, secretKey);
    const menus = JSON.parse(fs.readFileSync('./data/menus.json', 'utf-8'));
    
    res.json({
      success: true,
      code: 100,
      message: '获取用户信息成功',
      data: {
        id: 1,
        name: 'Admin',
        email: 'err@123.com',
        role: 'admin',
        _id: '1',
        deptId: '1',
        state: 1,
        // roleList: ['admin'],
        permissions: menus,
        roles: ['admin'],
        createId: '1',
        deptName: '技术部',
        mobile: '123456789',
        job: '资深前端开发',
        avatar: 'https://avatars.githubusercontent.com/u/499550?s=400&u=1c0d0d2c2c5c4b8f7b7f4f3f4f3f4f3f4f3f4f3&v=4',
        introduction: 'I am a super administrator',
        username: 'admin',

      }
    });
  } catch (error) {
    res.json({
      success: false,
      code: 401,
      message: '登录失效',
      data: null
    });
  }

});

// 找不到资源的话，返回404
app.use((req, res) => {
  res.status(404).json({ success: false, message: '找不到资源' });
});
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

